import { RouteRecordRaw } from 'vue-router'
const routeModules = import.meta.glob('../views/home/**/*.vue')
import * as AdminApi from '@/api'

/**
 *
 * @export routeToTree
 * @method routeToTree
 * @description 路由平铺数据转 tree 形数据 第一种方法
 * @param list
 * @returns
 * @author liu xu
 * @version 1.0.0
 * @date 2022.09.01
 */
export function routeToTree(list: any[]) {
  const parentList = list.filter((v: { pid: string }) => v.pid === '0')
  const childrenList = list.filter((v: { pid: string }) => v.pid !== '0')

  function routesToTree(parentList: any[], childrenList: any[]) {
    parentList.map((p: { id: any; children: any[] }) => {
      childrenList.map((c: { pid: any }, i: any) => {
        if (c.pid === p.id) {
          const _children = JSON.parse(JSON.stringify(childrenList))

          _children.splice(i, 1)
          routesToTree([c], _children)
          p.children ? p.children.push(c) : (p.children = [c])
        }
      })
    })
  }
  routesToTree(parentList, childrenList)

  return parentList
}

/**
 *
 * @export arrayToTree
 * @method arrayToTree
 * @description 路由平铺数据转 tree 形数据 第二种方法 (数据量很大时 性能好)
 * @param routes
 * @returns
 * @author liu xu
 * @version 1.0.0
 * @date 2022.09.01
 */

function arrayToTree(routes: Record<string, any>[]) {
  const result = [] // 存放结果集
  const routeMap: Record<string, any> = {}
  for (const routeItem of routes) {
    const { id, pid } = routeItem

    if (!routeMap[id]) {
      routeMap[id] = {
        children: [],
      }
    }
    routeMap[id] = {
      ...routeItem,
      children: routeMap[id]['children'],
    }

    const routeMapItem = routeMap[id]

    if (pid === '0') {
      result.push(routeMapItem)
    } else {
      if (!routeMap[pid]) {
        routeMap[pid] = {
          children: [],
        }
      }
      routeMap[pid].children.push(routeMapItem)
    }
  }
  return result
}

/**
 *
 * @export treeToRoutes
 * @method treeToRoutes
 * @description tree转换成对应的路由文件
 * @param routes
 * @returns
 * @author liu xu
 * @version 1.0.0
 * @date 2022.09.01
 */
const treeToRoutes = (routes: any[]): RouteRecordRaw[] => {
  return routes.map((item) => {
    const routes: Record<string, any> = {
      path: item.path,
      name: item.name,
      meta: {
        title: item.title,
        link: item.link,
        keepAlive: item.keepAlive ?? false,
        activeMenu: item.activeMenu ?? '',
        icon: item.icon,
      },
      component: routeModules[`../views/home/${item.component}.vue`],
      children: [],
    }

    item?.redirect && (routes['redirect'] = item?.redirect)

    if (item?.children?.length) {
      routes.children = treeToRoutes(item.children)
    }

    return routes
  }) as unknown as RouteRecordRaw[]
}

/**
 *
 * @export getAsyncRoutesOfRole
 * @method getAsyncRoutesOfRole
 * @description 模拟接口返回异步路由
 * @returns RouteRecordRaw[]
 * @author liu xu
 * @version 1.0.0
 * @date 2022.09.01
 */
export const getAsyncRoutesOfRole = async (): Promise<RouteRecordRaw[]> => {
  const routesByUser = await AdminApi.getRouterByUser()
  return new Promise((resolve) => {
    const routes = arrayToTree(routesByUser as unknown as Record<string, any>[])
    const accessRoutes = treeToRoutes(routes)

    resolve(accessRoutes)
  })
}

export function find(list, path) {
  let targetResult = null

  for (const item of list) {
    if (item.meta.link === path) {
      targetResult = item
    }

    if (item.children && item.children.length) {
      targetResult = find(item.children, path)

      if (targetResult) return targetResult
    }
  }

  return targetResult
}

export function getFirst(list) {
  if (!list.length) return null
  let result = list[0]

  if (result?.children?.length) {
    result = getFirst(result.children)
    if (result) return result
  }

  return result
}
